<?php
 /**
    * UserController class file
    *
    * @author Chamara Bandara
    * @copyright Copyright &copy; 2011 Allion Technologies (Pvt) Ltd
    */

Yii::import('application.extensions.simple_image');

class UserController extends RController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            //'accessControl', // perform access control for CRUD operations
            'rights',
        );
    }

   
    /*
     * allowed actions for all users
     */
    public function allowedActions() {
        return 'AjaxChangePassword,UpdatePassword';
    }

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('AjaxChangePassword', 'UpdatePassword'),
                'users' => array('*'),
            ),
            array('allow','users' => array('@'),
            ),
            array('allow','users' => array('chamara'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new User;
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->password)
                $model->password = User::model()->encryptPassword($_POST['User']['password']);
            $model->status = "Inactive";
            if (!$model->save()) {
                
            } else {
                $id = $model->getPrimaryKey();
                $paths = $this->createImageDirectories($id);
                $modelPicture = CUploadedFile::getInstance($model, 'picture');
                    
                if (isset($modelPicture) && !empty($modelPicture)) {
                    $rand = md5($this->generateRandomString());
                    $imageType = explode('image/', $modelPicture->getType());
                    $file = Yii::app()->params['imageSavePath'] . $paths['thumbnail'] . DIRECTORY_SEPARATOR . $rand . '.' . $imageType[1];
                    if ($modelPicture->saveAs($file))
                        $img = Yii::app()->simpleImage->load($file);
                    $img->resizeToWidth(128);
                    $img->save($file);
                    $model->picture = $paths['thumbnail'] . DIRECTORY_SEPARATOR . $rand . '.' . $imageType[1];
                    $model->save();
                        
                }
                 Yii::app()->user->setFlash('success', "User Created successfully!!");
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $picture = $model->picture;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if(!$model->picture)
                $model->picture = $picture;
            $paths = $this->createImageDirectories($id);

            $modelPicture = CUploadedFile::getInstance($model, 'picture');

            if (isset($modelPicture) && !empty($modelPicture)) {
                if (is_file(Yii::app()->params['imageSavePath'] . $model->picture)) {
                    unlink(Yii::app()->params['imageSavePath'] . $model->picture);
                }
                $rand = md5($this->generateRandomString());
                $imageType = explode('image/', $modelPicture->getType());
                $file = Yii::app()->params['imageSavePath'] . $paths['thumbnail'] . DIRECTORY_SEPARATOR . $rand . '.' . $imageType[1];
                if ($modelPicture->saveAs($file))
                    $img = Yii::app()->simpleImage->load($file);
                $img->resizeToWidth(128);
                $img->save($file);
                $model->picture = $paths['thumbnail'] . DIRECTORY_SEPARATOR . $rand . '.' . $imageType[1];
            }
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            $model = $this->loadModel($id);
            // we only allow deletion via POST request
            if (is_file(Yii::app()->params['imageSavePath'] . $model->picture)) {
                unlink(Yii::app()->params['imageSavePath'] . $model->picture);
                if (is_dir(Yii::app()->params['imageSavePath'] . $id))
                    rmdir(Yii::app()->params['imageSavePath'] . $id . DIRECTORY_SEPARATOR . 'thumbnail');
                rmdir(Yii::app()->params['imageSavePath'] . $id);
            }

            $model->delete();
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('User');
        $model = new User('search');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
            'model'=>$model,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new User('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['User']))
            $model->attributes = $_GET['User'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /*
     * action for foget password in login form to send a email for given email addrerss 
     * if it included in data base
     * 
     */
    public function ActionAjaxChangePassword() {
        if (Yii::app()->request->getIsAjaxRequest()) {

            $modelEmail = User::model()->findByAttributes(array('email' => $_POST['email'], 'status' => "Active"));
            if ($modelEmail) {
                $message = new YiiMailMessage;
                $message->view = "mailTemplate";
                $message->subject = 'Change Password';
                //create tokenid
                $token = $this->generateRandomString();
                $model = new FogetPassword();
                $model->tokenid = $token;
                $model->user_id = $modelEmail->id;
                if ($model->save())
                    $url = Yii::app()->createAbsoluteUrl('user/UpdatePassword?id='.$token);
                $params = array('mailMassage' => $modelEmail, 'link' => $url);
                $message->setBody($params, 'text/html');
                $message->addTo($_POST['email']);
                $message->from = Yii::app()->params['fromEmail'];
                Yii::app()->mail->send($message);

                echo 'valid';
                exit;
            }else {
                echo 'invalid';
                exit;
            }
        }
    }
    
    /*
     * action for change password when click on the email url
     * 
     */
    public function ActionUpdatePassword() {
        if (isset($_GET['id'])) {
            $model_fogotpsw = FogetPassword::model()->findByAttributes(array('tokenid' => $_GET['id']));
            if (!is_null($model_fogotpsw)) {
                $model = $this->loadModel($model_fogotpsw->user_id);
            } else {
                $model = new User();
                Yii::app()->user->setFlash('error', "Your Token Expired!!  try again >>");
            }
            if (isset($_POST['User'])) {
                $model->password = User::model()->encryptPassword($_POST['User']['new_password']);

                if (!$model->save()) {
                    print_r($model->getErrors());
                    exit;
                } else {
                    Yii::app()->user->setFlash('success', "Your Password Reset successfully!!  Go to Login >>");
                }
            }

            $this->render('resetPassword', array(
                'model' => $model,
            ));
        }
    }

    /*
     * create image derectories for upload user image
     */
    protected function createImageDirectories($id) {
        $path = array();
        $imagePath = Yii::app()->params['imageSavePath'];
        //print_r($imagePath);exit;

        if (!is_dir($imagePath)) {
            if (!mkdir($imagePath, 0755, true)) {
                throw new CHttpException(500, 'Could not create the directory structure for user image.');
            }
        }
        if (!is_dir($imagePath . DIRECTORY_SEPARATOR . $id)) {
            if (mkdir($imagePath . DIRECTORY_SEPARATOR . $id))
                mkdir($imagePath . DIRECTORY_SEPARATOR . $id . DIRECTORY_SEPARATOR . 'thumbnail');
        }

        $path['thumbnail'] = $id . DIRECTORY_SEPARATOR . 'thumbnail';
        return $path;
    }
    
    /*
     * function for create random string
     */
    public static function generateRandomString($length = 32) {
        $chars = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
        shuffle($chars);
        return implode('', array_slice($chars, 0, $length));
    }

    /*
     * action for approve users after create(only super admin  can perfom this operation )
     */
    
    public function actionApprove() {
        $model = new User();
        if (isset($_GET['id']))
            User::model()->updateAll(array('status' => "Active"), 'id="' . $_GET['id'] . '"');
        $model->unsetAttributes();
        $model = new User();
        $this->redirect('?r=/user/admin', array(
            'model' => $model,
        ));
    }

     /*
     * action for reject users after create(only super admin  can perfom this operation )
     */
    
    public function actionDisApprove() {
        $model = new User();
        if (isset($_GET['id']))
            User::model()->updateAll(array('status' => "Inactive"), 'id="' . $_GET['id'] . '"');
        $model->unsetAttributes();
        $model = new User();
        $this->redirect('?r=/user/admin', array(
            'model' => $model,
        ));
    }

    /*
     * aaction for update user password(reset password) in profile view
     */
    public function actionAjaxUpdatePassword() {
        if (Yii::app()->request->getIsAjaxRequest()) {
            $model = $this->loadModel($_POST['uid']);

            $model->password = User::model()->encryptPassword($_POST['npsw']);

            if (!$model->save()) {
                echo 'Invalid';
                exit;
                exit;
            } else {
                echo 'valid';
                exit;
            }
        }
    }

}
